import { def } from './util';
import Observer from './Observer';

const changedMethods = [
    'push',
    'pop',
    'shift',
    'unshift',
    'splice',
    'sort',
    'reverse'
]

const arrayPrototype = Array.prototype;
//以Array.prototype为原型创建arrayMethods
export const arrayMethods = Object.create(arrayPrototype);

changedMethods.forEach(methodName => {
    //备份原始方法
    const original = arrayMethods[methodName];
    //创建新方法
    def(arrayMethods, methodName, function(a) {
        console.log(a);
        //恢复原来函数功能
        const result = original.apply(this, arguments);
        const args = [...arguments];
        //把这个数组的__obj__取出来
        let ob = this.__obj__;
        let inserted = [];
        switch (methodName) {
            case "push":
            case "unshift":
                inserted = args;
                break;
            case "splice":
                //splice(下标，数量，插入新项)
                inserted = args.slice(2);
                break;

            default:
                break;
        }
        if (inserted) {
            if (!ob) {
                ob = new Observer(inserted)
            }
            ob.observeArray(inserted);
        }
        ob.dep.notify();
        return result;
    }, false);
});